package error_handler

import (
	"fmt"
	"github.com/pkg/errors"
	log "github.com/sirupsen/logrus"
	"io/ioutil"
	"net/http"
)

func ExitWenError(err error) {
	if err != nil {
		info := fmt.Sprintf("%+v\n", err)
		log.Fatal(info)
	}
}

func PrintError(err error, msg ...string) {
	if err != nil {
		info := fmt.Sprintf("%+v\n", err)
		if len(msg) > 0 {
			log.Error(msg)
		}
		log.Error(info)
	}
}

func AssertResponseOk(resp *http.Response, err error) {
	if err != nil {
		HttpPanicIfError(err)
	} else if resp.StatusCode >= 400 {
		all, _ := ioutil.ReadAll(resp.Body)
		HttpPanicIfError(errors.New(string(all)))
	}
}

func HttpPanicIfError(err error, msg ...string) {
	if err != nil {
		info := fmt.Sprintf("%+v\n", err)
		if len(msg) > 0 {
			log.Error(msg)
		}
		log.Error(info)
		panic(err)
	}
}

func HttpPanicHandler(writer http.ResponseWriter, request *http.Request, i interface{}) {
	//_, ok := i.(NotFoundError)
	//if ok {
	//	writer.WriteHeader(http.StatusNotFound)
	//} else {
	writer.WriteHeader(http.StatusInternalServerError)
	//}

	if i != nil {
		content := fmt.Sprintf("%v", i)
		_, _ = writer.Write([]byte(content))
	}
}
